// ActionScript file

import control.Control;

import events.IEvent;

import flash.events.Event;
import flash.events.KeyboardEvent;

import model.ModelLocator;

import mx.collections.IViewCursor;
import mx.collections.Sort;
import mx.collections.SortField;
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;

import vo.Ware;
flash.system.System.useCodePage= true;
[Bindable]
public var instance:ModelLocator = ModelLocator.GetInstance();
private var controlor:Control = new Control();

// the global popup window
internal var win:*;
// 初始化要求登录
internal function InitApp( obj:Object):void
{
	Alert.okLabel = "确定";
	Alert.cancelLabel = "取消";
	if( instance.isLogin == false )
	{ 
		win = new LoginPanel();
		PopUpManager.addPopUp( win, this, true );
		PopUpManager.centerPopUp(win );
	}
	application.addEventListener( KeyboardEvent.KEY_UP, KeyUpHandler );
	instance.addEventListener( IEvent.TYPECHANGED, controlor.GetType );
	instance.addEventListener( IEvent.TYPEUPDATED, controlor.UpdateWareType );
	instance.addEventListener( IEvent.TYPEUPDATED, controlor.UpdateTypeCombo );
	instance.addEventListener( IEvent.ADDWAREOK, AddWareOKHandler );
	instance.addEventListener( IEvent.CLIENTADDED, function(evt:Event):void
		{
			controlor.GetClientList(null);
			Alert.show( "成功添加!", "成功", Alert.OK, null, ClosePopUp);
		} );
	instance.addEventListener( IEvent.CLIENTDELETED, function(evt:Event ):void
		{
			controlor.GetClientList(null);
			Alert.show( "已删除!");
		} );
	instance.addEventListener( IEvent.CLIENTUPDATED, function( evt:Event):void
		{
			controlor.GetClientList(null);
			Alert.show( "已更新!");
		} );
	instance.addEventListener( IEvent.DELETEWAREOK, controlor.GetWareList );
	instance.addEventListener( IEvent.UPDATEWAREOK, function(evt:Event):void
		{
			ClosePopUp(null);
			Alert.show( "商品已更新", "成功");
			controlor.GetWareList(null);
		} );
	instance.addEventListener( IEvent.TICKETLISTCHANGED, instance.UpdateTicketStat );
	// 操作成功
	instance.addEventListener( IEvent.OPERATIONSUCCEED, function(evt:Event):void
		{
			Alert.show( "操作成功", "提示" );
		} );
	instance.addEventListener( IEvent.OPERATIONFAILED, function( evt:Event):void
	{
		Alert.show( "刚刚的操作不成功!", "提示" );
	});
	instance.addEventListener( IEvent.INSERTTICKET, function( evt:Event ):void
		{
			Alert.show( "成功添加!", "成功");
			//controlor.GetTicketList( null );
			instance.ticketWareList.removeAll();
			Misc.text = "";
			UpdateTotalAmount();
			RealPay.text = "";
		} );
	//controlor.GetType( null );
}
internal function KeyUpHandler( evt:KeyboardEvent ):void
{
	if( evt.keyCode == 13 && evt.ctrlKey == true && mainStack.selectedChild.id == "TicketInput" )
	{
		SubmitTicket();
	}
}
internal function AddWareOKHandler(evt:Event):void
{
	controlor.GetWareList(null);
	Alert.show( "成功添加!", "成功", Alert.OK, null, ClosePopUp);
}
internal function ClosePopUp( evt:Event):void
{
	PopUpManager.removePopUp( win );
} 
internal function Logout():void
{
	manuClick("UserDetail");
	instance.isLogin = false;
	Alert.show( "你已经安全登出", "提示", Alert.OK, null,LogoutHandler);
	instance.dispatchEvent( new Event( IEvent.LOGIN_OUT ) );
}
internal function LogoutHandler(evt:Event):void
{
	if( instance.isLogin == false )
	{
		win = new LoginPanel();
		PopUpManager.addPopUp( win, this, true );
		PopUpManager.centerPopUp(win );
	}
}
internal function manuClick( operation:String ):void
{
	
	switch ( operation )
	{
		case "TicketInput":
			mainStack.selectedChild = TicketInput;
			if(TicketTypeCombo.selectedItem != null && TicketTypeCombo.selectedItem.data != null )
			{
				instance.wareList.filterFunction = function(item:Object):Boolean
							{
								trace(item.type+"===="+TicketTypeCombo.selectedItem.data)
								return item.type == TicketTypeCombo.selectedItem.data; 
							}
			}
			else
			{
				instance.wareList.filterFunction = null;
			}
			instance.wareList.refresh();
			
			break;
		case "ProductManage":
			instance.wareList.filterFunction = null;
			instance.wareList.refresh();
			controlor.GetWareList(null);
			mainStack.selectedChild = ProductManage;
			break;
		case "TypeManage":
			controlor.GetType( null );
			mainStack.selectedChild = TypeManage;
			break;
		case "TicketManage":
			mainStack.selectedChild = TicketManage;		
			break;
		case "UserMange":
			controlor.GetUserList();
			mainStack.selectedChild = UserMange;
			break;
		case "UserDetail":
			mainStack.selectedChild = UserDetail;
			break;
		case "TraceRecord":
			mainStack.selectedChild = TraceRecord;
			break;
		case "ClientManage":
			controlor.GetClientList(null);
			instance.clientList.filterFunction = null;
			instance.clientList.refresh();
			mainStack.selectedChild = ClientManage;
			if( SearchName != null )
			{
				SearchName.text = "";
			}
			if( SearchPhone != null )
			{
				SearchPhone.text = "";
			}
			break;
	}
}

internal function AddType():void
{
	//Alert.show(TypeList.selectedIndex.toString());
	//return;
	if( AddTypeNameInput.text == "" )
	{
		Alert.show( "没有输入类别名称" );
		return;
	}
	controlor.AddType( AddTypeNameInput.text, AddTypeMiscInput.text );
}
internal function DeleteType( id:int):void
{
	Alert.show( "确定删除选中的项目?\n此项操作可能会影响到该类别的商品.","删除",Alert.OK|Alert.CANCEL,null,function(evt:CloseEvent):void
	{
		if( evt.detail == Alert.OK )
			controlor.DeleteType( id );
	});
}
internal function EditType( id:int, name:String, misc:String):void
{
	if( AddTypeNameInput.text == "" )
	{
		Alert.show( "没有输入类别名称" );
		return;
	}
	controlor.EditType( id, name, misc );
}
public function sortcompare(obj1:Object,obj2:Object):int
{
	var num1:Number=Number(obj1.id.toString());
    var num2:Number=Number(obj2.id.toString());
    if(num1>num2){
    	return 1;
    }else if(num1<num2){
    	return -1;
    }else{
    	return 0;
   }
}
// Client operation:
public function ShowAllClient():void
{
	SearchName.text = "";
	SearchPhone.text = "";
	instance.clientList.filterFunction = null;
	instance.clientList.refresh();
}
public function EditClient( id:int ):void
{
	Alert.show( "确定更新选中的客户资料?","确定",Alert.OK|Alert.CANCEL,null,function(evt:CloseEvent):void
	{
		if( evt.detail == Alert.OK )
			controlor.EditClient( id, ClientName.text, ClientCompany.text, ClientType.text, ClientAddress.text,
					ClientPhone1.text, ClientPhone2.text, ClientPhone3.text, ClientMisc.text );
	});
}
public function AddClient():void
{
	win = new AddClientPanel();
	PopUpManager.addPopUp( win, this, true );
	PopUpManager.centerPopUp( win );
}
public function ExportPhone():void
{
	ShowAllClient();
	win = new ExportPhonePanel();
	PopUpManager.addPopUp( win, this, true );
	PopUpManager.centerPopUp( win );
}
public function DeleteClient(id:int ):void
{
	Alert.show( "确定删除选中的客户?","删除",Alert.OK|Alert.CANCEL,null,function(evt:CloseEvent):void
	{
		if( evt.detail == Alert.OK )
			controlor.DeleteClient( id );
	});
}
internal function AddWare():void
{
	win = new AddWarePanel();
	PopUpManager.addPopUp( win, this, true );
	PopUpManager.centerPopUp( win );
}
public function DeleteWare( id:int ):void
{
	
	Alert.show( "确定删除选中的项目?","删除",Alert.OK|Alert.CANCEL,null,function(evt:CloseEvent):void
	{
		if( evt.detail == Alert.OK )
			controlor.DeleteWare( id );
	});
}
public function EditWare():void
{

	instance.editWare = new Ware();
	for( var i:int = 0; i < instance.wareList.length; i ++ )
	{
		if( instance.wareList[i].id == WareList.selectedItem.id )
		{
			instance.editWare = instance.wareList[i];
			break;
		}
	}
	win = new EditWarePanel(); 
	PopUpManager.addPopUp( win, this,true );
	PopUpManager.centerPopUp( win );
}
public function TypeChange(evt:Event):void
{
	if(evt.target.selectedItem.data == null )
	{
		instance.wareList.filterFunction = null;
	}
	else
	{
		instance.wareList.filterFunction = function(item:Object):Boolean
					{
						trace(item.type+"===="+evt.target.selectedItem.data)
						return item.type == evt.target.selectedItem.data; 
					}
	}
	instance.wareList.refresh();
	instance.dispatchEvent( new Event( IEvent.TYPECOMBOCHANGE ) );
}
public function PhoneSearch(evt:Event):void
{
	SearchName ? SearchName.text = "" : null;
	TicketSearchName ? TicketSearchName.text = "" : null;
	if( evt.target.text == "" )
	{
		instance.clientList.filterFunction = null;
	}
	else
	{
		instance.clientList.filterFunction = function( item:Object):Boolean
					{
						if( item.phone1.indexOf(evt.target.text ) >=0 
								|| ( item.phone2.indexOf(evt.target.text ) >=0 )
								|| ( item.phone3.indexOf(evt.target.text ) >=0 ) )
						{
							return true;
						}
						else
						{
							return false;
						}
					}
	}
	instance.clientList.refresh();
	ClientList?ClientList.dataProvider =instance.clientList:null; 
}
public function NameSearch(evt:Event):void
{
	SearchPhone ? SearchPhone.text = "" : null;
	TicketSearchPhone ? TicketSearchPhone.text = "" : null;
	if( evt.target.text == "" )
	{
		instance.clientList.filterFunction = null;
	}
	else
	{
		instance.clientList.filterFunction = function( item:Object):Boolean
					{
						if( item.name.indexOf(evt.target.text ) >=0 )
						{
							return true;
						}
						else
						{
							return false;
						}
					}
	}
	instance.clientList.refresh();
	ClientList?ClientList.dataProvider =instance.clientList:null; 
}
public function TypeChangeInWareList(evt:Event):void
{
	if(evt.target.selectedItem.data == null )
	{
		instance.wareList.filterFunction = null;
	}
	else
	{
		instance.wareList.filterFunction = function(item:Object):Boolean
					{
						trace(item.type+"===="+evt.target.selectedItem.data)
						return item.type == evt.target.selectedItem.data; 
					}
	}
	instance.wareList.refresh();
	WareList.dataProvider = instance.wareList;
}
public function WareComboChange():void
{
	Price.text = "";
	WareNumber.text = "";
}
public function AddToTicketWareList():void
{
	if(TicketWareCombo.selectedIndex < 0)
	{
		Alert.show( "请选择商品" );
		return;
	}
	else if( WareAmount.text== "0")
	{
		Alert.show( "价格或数量不正确, 请重新输入." );
		return;
	}
	
	instance.ticketWareList.addItem({id:TicketWareCombo.selectedItem.id,
									 name:TicketWareCombo.selectedItem.name,
									 typeId:TicketWareCombo.selectedItem.type,
									 typeName:TicketWareCombo.selectedItem.typeName,
									 price:Price.text,
									 wareNumber:WareNumber.text,
									 wareAmount:WareAmount.text });
	UpdateTotalAmount();
}
public function RemoveWare():void
{
	var findIndex:int = instance.ticketWareList.getItemIndex(CurTicket.selectedItem);
	if( findIndex < 0 )
	{
		Alert.show(CurTicket.selectedItem.id);
		return;
	}
	
	var obj:Object = instance.ticketWareList.removeItemAt(findIndex);
	if( obj )
	{
		Alert.show( obj.name+"已经从列表删除" );
	}
	UpdateTotalAmount();
}
public function SubmitTicket():void
{
	if( TicketLocation.selectedItem.data == null )
	{
		Alert.show( "请选择分店" );
		return;
	}
	else if( TicketDate.text == "" )
	{
		Alert.show( "请选择订单的日期" );
		return;
	}
	else if( CheckboxAddClient.selected == true && TicketClientList.selectedItem == null )
	{
		Alert.show( "请选择一个用户");
		return;
	}
	Alert.show( "日期: "+TicketDate.text+"\n分店: "+TicketLocation.selectedItem.label +"\n总价: " + TotalAmount.text + "元\n实收: " + RealPay.text + "元\n确认要提交吗?","提交?", Alert.OK|Alert.CANCEL,null, function(evt:CloseEvent):void
				{
					var clientId:int = 0
					if( CheckboxAddClient.selected == true )
					{
						clientId = TicketClientList.selectedItem.id;
					}
					if( evt.detail == Alert.OK )
					{
						controlor.SubmitTicket(TicketLocation.selectedItem.label,TicketLocation.selectedItem.data, TotalAmount.text, RealPay.text,TicketDate.text,Misc.text,clientId);
					}
				});
}
public function UpdateTotalAmount():void
{
	var totalAmount:Number = 0;
	for( var i:int = 0; i < instance.ticketWareList.length; i ++ )
	{
		totalAmount+=Number( instance.ticketWareList[i].wareAmount );
	}
	RealPay.text=TotalAmount.text = totalAmount.toString();
}
public function DeleteTicket():void
{
	controlor.DeteleTicket( TicketList.selectedItem.id );
}
public function TicketListChange():void
{
	instance.ticketDetails.removeAll();
	controlor.ShowTicketDetails(TicketList.selectedItem.id);
}
public function QueryTicket():void
{
	var curDate:Date = new Date();
	var startDate:String = curDate.getFullYear()+"-"+(curDate.getMonth()+1).toString()+"-"+curDate.getDate();
	if( CheckTicketDate1.text !="")
	{
		startDate = CheckTicketDate1.text;
	}
	var endDate:String = "";
	if( CheckTicketDate2.text != "" )
	{
		endDate = CheckTicketDate2.text;
	}
	else
	{
		endDate = curDate.getFullYear()+"-"+(curDate.getMonth()+1).toString()+"-"+curDate.getDate();
	}
	controlor.GetTicketList( null, startDate, endDate,ChenckTicketClientPhone.text,ChenckTicketClientName.text );
}
public function GetTraceList():void
{
	var curDate:Date = new Date();
	var startDate:String = curDate.getFullYear()+"-"+(curDate.getMonth()+1).toString()+"-"+curDate.getDate();
	if( CheckTraceDate1.text !="")
	{
		startDate = CheckTraceDate1.text;
	}
	var endDate:String = "";
	if( CheckTraceDate2.text != "" )
	{
		endDate = CheckTraceDate2.text;
	}
	else
	{
		endDate = curDate.getFullYear()+"-"+(curDate.getMonth()+1).toString()+"-"+curDate.getDate();
	}
	controlor.GetTraceList( null, startDate, endDate );
}
public function AddUser():void
{
	var sort:Sort= new Sort();
    sort.fields = [new SortField("name", true)];
    instance.userList.sort = sort;
    var cursor:IViewCursor = instance.userList.createCursor();
	// 移除过滤条件, 在整个表中查找.
	instance.userList.filterFunction = null;
	instance.userList.refresh();
	var isExistUser:Boolean = cursor.findFirst({name:NewUserInput.text});
	if(isExistUser)
	{
		Alert.show( "已经有名字为\""+NewUserInput.text+"\"的用户存在\n请重新命名","用户名重复");
		return;
	}
	
	var permission:int = 0;
	if(NewUserPermissionInput.text.length >=0 )
	{
		if( int( NewUserPermissionInput.text ) >10 || int( NewUserPermissionInput.text ) < 0 )
		{
			Alert.show( "权限值必须在0到10之间" );
			return;
		}
		permission = int( NewUserPermissionInput.text );
	}
	controlor.Regist( NewUserInput.text,permission, "888888","");
}
public function ResetPass():void
{
	if( UserList.selectedIndex < 0 )
	{
		Alert.show( "必须选中一个用户","无效用户");
		return;
	}
	controlor.ResetPass( UserList.selectedItem.name );
}
public function DeleteUser():void
{
	if( UserList.selectedIndex < 0 )
	{
		Alert.show( "必须选中一个用户","无效用户");
		return;
	}
	Alert.show( "确定要删除用户\""+UserList.selectedItem.name+"\"?", "删除用户", Alert.OK|Alert.CANCEL,null, function( evt:CloseEvent ):void
						{
							if( evt.detail == Alert.OK )
							controlor.DeleteUser( UserList.selectedItem );
						} );

}
public function SubmitUserDetail():void
{
	if( PassInput.text.length == 0 )
	{
		return;
	}
	else if ( PassInput.text != ConfirmPassInput.text )
	{
		Alert.show( "重复密码与密码不一致" );
		return;
	}
	controlor.ResetPass( instance.curUser.name, PassInput.text );
	PassInput.text = ConfirmPassInput.text = "";
}